<template>
  <el-page-header @back="goBack" style="margin: 20px 50px">
    <template #content>
      <span class="text-large font-600 mr-3"> 店铺详情 </span>
    </template>
    <template #extra>
      <div class="flex items-center">
        <el-button
          type="primary"
          class="ml-2"
          @click="ShoppingCart(route.params.id)"
          >购物车</el-button
        >
      </div>
    </template>
  </el-page-header>
  <div class="shop-detail">
    <img :src="shopData.cover" alt="店铺Logo" style="width: 300px" />
    <div class="text">
      <h3>
        欢迎光临-{{ shopData.name }}
        <el-tooltip v-if="!isCollect" content="觉得喜欢就收藏一下吧">
          <el-icon @click="changeCollectStatus()"><Star /></el-icon>
        </el-tooltip>
        <el-tooltip v-else content="您确定要取消收藏吗">
        <el-icon @click="changeCollectStatus()"><StarFilled /></el-icon>
      </el-tooltip>
      </h3>
      <h5>
        <el-icon><Location /></el-icon>店铺地址：{{ shopData.address }}
      </h5>
      <h5>
        <el-icon><PhoneFilled /></el-icon>联系电话：{{ shopData.contact }}
      </h5>
      <h5>
        <el-icon><Shop /></el-icon>综合评分：<span style="color: #c00">{{
          shopData.star
        }}</span>
      </h5>
    </div>
    <div class="text">
      <div style="display: flex; align-items: center">
        <h5>详细介绍：</h5>
        <p style="color: #666; font-size: 12px">{{ shopData.detail }}</p>
      </div>
    </div>
  </div>
  <el-tabs type="border-card" v-model="activeName" style="margin: 0 50px">
    <el-tab-pane label="菜品" name="first">
      <div class="dishes-list">
        <el-row>
          <el-col style="margin-top: 20px" :span="4">
            <el-menu
              default-open
              :default-active="defaultActive"
              @select="handleCategorySelect"
              class="category-menu"
            >
              <el-menu-item
                v-for="(category, index) in categories"
                :key="index"
                :index="category.id.toString()"
              >
                {{ category.name }}
              </el-menu-item>
            </el-menu>
          </el-col>

          <el-col :span="16" style="display: flex; flex-wrap: wrap">
            <el-card
              class="dishes-card"
              v-for="(dish, index) in dishesList"
              :key="index"
              :body-style="{ padding: '0px' }"
            >
              <img :src="dish.pic" class="image" />
              <div class="text">
                <span>{{ dish.name }}</span>
                <span class="description">{{ dish.description }}</span>
                <span class="number"
                  >数量:<el-input-number v-model="quantity" :min="0" :max="10"
                /></span>
                <el-button
                  style="margin-top: 10px"
                  type="primary"
                  @click="addToCart(dish.id)"
                  >加入购物车</el-button
                >
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-tab-pane>
    <el-tab-pane label="评论">
      <div class="eval" v-for="(item,index) in evaluations" :key="index">
        <img style="width: 55px;border-radius: 50%;" :src="item.avatar">
        <span class="dishes-detail">{{ item.detail }}</span>
        <span class="star"><el-rate v-model="item.star" size="large" disabled score-template="{{item.star}} points"/></span>
        <span class="evaluation">用户{{item.userNickname}}说“{{ item.evaluate }}”</span>
        <span class="time">于{{ item.createTime }}购买</span>
      </div>
      <el-pagination
          style="margin-top: 20px;"
          v-model:current-page="searchParams.pageNum"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="parseInt(totalItems)"
          @size-change="searchList"
          @current-change="searchList"
        />
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { detailApi, categoryApi, dishesApi,evalApi,collectApi,saveCollectApi } from '@/api/shop-detail'
import { addCartApi } from '@/api/shopping-cart'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'

export default {
  data() {
    return {
      quantity: 0
    }
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const dataDetail = reactive({
      shopData: {},
      searchParams: {
        pageNum: 1,
        pageSize: 5,
        shopId:route.params.id
      },
      totalItems: '',
      evaluations:[],
      isCollect: ''
    })
    const dishes = reactive({
      categories: [],
      dishesList: []
    })
    const defaultActive = ref('')
    const activeCategory = ref('')
    const activeName = ref('first')
    const detail = () => {
      detailApi({ id: route.params.id }).then((res) => {
        if (res.data) {
          dataDetail.shopData = res.data
          categoryApi({ shopId: route.params.id }).then((cate) => {
            if (cate.data.length != 0) {
              dishes.categories = cate.data
              defaultActive.value = cate.data[0].id.toString()
              activeCategory.value = cate.data[0].id
              dishesApi({ shopId: route.params.id }).then((ds) => {
                dishes.dishesList = ds.data.filter(
                  (dish) => dish.category == activeCategory.value
                )
              })
            }
          })
        }
      })
    }

    const searchList = () => {
      evalApi(dataDetail.searchParams).then((res) => {
        if (res.data) {
          dataDetail.evaluations = res.data.content
          dataDetail.totalItems = res.data.totalSize
        }
      })
    }
    const ShoppingCart = (id) => {
      router.push({
        name: 'ShoppingCart',
        params: { id: id }
      })
    }
    const goBack = () => {
      window.history.back()
    }
    const getCollect=()=>{
      collectApi({shopId:route.params.id}).then((res)=>{
        if(res.isCollect==1){
          dataDetail.isCollect=true
        }else{
          dataDetail.isCollect=false
        }
      })
    }
    const changeCollectStatus=()=>{
      saveCollectApi({shopId:route.params.id}).then((res)=>{
        if(res.data==1){
          dataDetail.isCollect=!dataDetail.isCollect
          ElMessage({
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        }
      })
    }
    getCollect()
    searchList()
    detail()
    return {
      defaultActive,
      activeCategory,
      goBack,
      ...toRefs(dataDetail),
      ...toRefs(dishes),
      ShoppingCart,
      store,
      route,
      activeName,
      searchList,
      changeCollectStatus
    }
  },
  methods: {
    addToCart(dishId) {
      // 获取数量
      const quantity = this.quantity
      const selectedDish = this.dishesList.find((dish) => dish.id === dishId)
      if (quantity <= 0) {
        ElMessage({
          message: '数量不能为0',
          type: 'error',
          duration: 2000
        })
      } else {
        const shoppingCartItem = {
          dishesId: selectedDish.id,
          quantity: quantity,
          shopId: this.route.params.id,
          userId: this.store.state.uInfo.userInfo.userId
        }
        addCartApi(shoppingCartItem).then((res) => {
          if (res) {
            ElMessage({
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      }
    },
    handleCategorySelect(key) {
      this.activeCategory = parseInt(key)
      this.quantity = 0
      dishesApi({ shopId: this.route.params.id }).then((ds) => {
        this.dishesList = ds.data.filter((dish) => dish.category == key)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.shop-detail {
  display: flex;
  align-items: center;
  margin: 20px 50px;
}
.shop-detail .text {
  margin-left: 50px;
}
.dishes-list {
  margin: 20px 50px;
}
.dishes-card {
  width: 30%;
  margin: 10px;
}
.dishes-card img {
  width: 100%;
  display: block;
}
.dishes-card .description {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}
.dishes-card .text {
  display: flex;
  flex-direction: column;
  padding: 14px;
}
.dishes-card .number {
  margin-top: 10px;
}

.eval{
  display: flex;
  align-items: center;
  margin: 10px;
}
.eval .dishes-detail{
  width: 100px;
  margin: 0 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.eval .evaluation{
  flex: 1;
  margin: 0 10px;
  white-space: wrap;
}
.eval .time{
  color: #999;
  font-size: 12px;
}
</style>
